#import "LGImageCollectionCell.h"
#import "TUIDefine.h"
#import "TUITool.h"
@interface LGImageCollectionCell ()<UIGestureRecognizerDelegate>

/**   */
@property (nonatomic , strong)UIScrollView *scrollView;

@end
@implementation LGImageCollectionCell
- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        [self setupViews];
    }
    return self;
}

- (void)setupViews{
    self.clipsToBounds = YES;
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    self.scrollView.contentSize = CGSizeMake(Screen_W, Screen_H);
    [self.contentView addSubview:self.scrollView];
    
    self.imageView = [[UIImageView alloc] init];
    self.imageView.layer.cornerRadius = 5.0;
    [self.imageView.layer setMasksToBounds:YES];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:self.imageView];
    self.imageView.mm_fill();
    self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    // 添加缩放手势
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    pinchGesture.delegate = self;
    [self.contentView addGestureRecognizer:pinchGesture];
    
    self.downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.downloadBtn.contentMode = UIViewContentModeScaleToFill;
    [self.downloadBtn setImage: TUIChatCommonBundleImage(@"download") forState:UIControlStateNormal];
    [self.downloadBtn addTarget:self action:@selector(onDownloadBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.downloadBtn];
    
    self.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSelectMedia)];
    [self addGestureRecognizer:tap];
}

#pragma mark - 缩放手势处理
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)gesture {
    // 缩放图片视图
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        NSLog(@">>>???>>>%f",gesture.scale);
        CGFloat imageW = self.imageView.bounds.size.width*gesture.scale;
        CGFloat imageH = self.imageView.bounds.size.height*gesture.scale;
        CGFloat contentW = imageW>Screen_W?imageW:Screen_W;
        CGFloat contentH = imageH>Screen_H?imageH:Screen_H;
        self.scrollView.contentSize = CGSizeMake(contentW, contentH);
        self.imageView.bounds = CGRectMake(0, 0, imageW, imageH);
        self.imageView.center = CGPointMake(contentW/2.0, contentH/2.0);
        if (contentW>Screen_W) {
            self.scrollView.contentOffset = CGPointMake((contentW-Screen_W)/2.0, (contentH-Screen_H)/2.0);
        }
        gesture.scale = 1.0; // 重置手势缩放值
    }else if (gesture.state == UIGestureRecognizerStateEnded){
        //结束
        CGFloat imageW = self.imageView.bounds.size.width;
        if (imageW < Screen_W) {
            [UIView animateWithDuration:0.2 animations:^{
                self.imageView.mm_fill();
                self.imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            }];
        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (void)onDownloadBtnClick {
    UIImage *image = self.imageView.image;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                [TUITool makeToast:TUIKitLocalizableString(TUIKitPictureSavedSuccess)];
            } else {
                [TUITool makeToast:TUIKitLocalizableString(TUIKitPictureSavedFailed)];
            }
        });
    }];
}

- (void)onSelectMedia {
    if (self.delegate && [self.delegate respondsToSelector:@selector(onCloseMedia:)]) {
        [self.delegate onCloseMedia:self];
    }
}

- (void)fillWithMediaData:(NSDictionary *)dataDic{
    [super fillWithMediaData:dataDic];
    NSArray *photoArray = dataDic[@"content"];
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:LGNSString([photoArray firstObject][@"url"])]];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.downloadBtn.mm_width(31).mm_height(31).mm_right(16).mm_bottom(48);
}
@end
